import * as fs from 'fs/promises';
import path from "path";
import sharp from "sharp";
import { app, BrowserWindow, dialog, clipboard  } from "electron";

const get_base_path = (data)=>{
  let json_path;
  if (app.isPackaged) {
    // 打包后路径（如 resources/app.asar/public/data.json）
    json_path = path.join(process.resourcesPath, data);
  } else {
    // 开发环境路径
    json_path = data;
  }
  return json_path;
};

const get_config = async (e, data) => {
  const json_path = get_base_path(data);
  try {
    const file_data = await fs.readFile(json_path, "utf-8");
    return JSON.parse(file_data);
  } catch (err) {
    return false;
  }
};

const open_dialog = async (e, data) => {
  // 查找与 WebContents 关联的 BrowserWindow
  const window = BrowserWindow.fromWebContents(e.sender);
  if (window) {
    try {
      let result = await dialog.showOpenDialog(window, {
        title: "选择文件",
        properties: ["openFile"], // 允许选择文件、文件夹或多个
        filters: [
          {
            name: "Images",
            extensions: data.list,
          },
        ],
      });

      if (!result.canceled) {
        const data = await fs.readFile(result.filePaths[0]);
        const base64 = `data:image/png;base64,${data.toString("base64")}`;
        return base64;
      }
    } catch (err) {
      return "获取文件失败";
    }
  }
};

const get_save_path = async (e, data) => {
  let defaultFilename = app.getPath("downloads"); // 默认文件夹路径
  // 查找与 WebContents 关联的 BrowserWindow
  const window = BrowserWindow.fromWebContents(e.sender);
  const result = await dialog.showOpenDialog(window, {
    title: "请选择图片保存位置",
    properties: ["openDirectory"], // 允许选择文件夹
    defaultPath: defaultFilename,
  });
  if (!result.filePaths[0] || result.canceled) {
    // 用户取消了保存操作
    return null;
  }
  return result.filePaths[0];
};

const save_file = async (e, data) => {
  // base64Data, outputDir, fileExtension
  try {
    // 生成唯一文件名（或自定义名称）
    let file_name;
    if (data.file_name) {
      file_name = `${data.file_name}.${data.file_extension}`;
    } else {
      file_name = `output_${Date.now()}.${data.file_extension}`;
    }
    const output_path = path.join(data.output_dir, file_name);

    // 移除 Base64 前缀（如 "data:image/jpeg;base64,"）
    const base64_content = data.base64_data.replace(
      /^data:image\/\w+;base64,/,
      ""
    );
    // 将 Base64 转为 Buffer
    const image_buffer = Buffer.from(base64_content, "base64");
    // 使用 Sharp 处理并保存图片
    await sharp(image_buffer)
      .resize({
        width: data.width,
        height: data.height,
        fit: "inside", // 覆盖整个区域（可能裁剪）
      })
      .toFile(output_path);
    // await sharp(image_buffer)
    //   .resize(32, 32) // 提取 32x32 尺寸（ICO 通常包含多尺寸）
    //   .toFile(output_path);
    return "保存成功";
  } catch (err) {
    console.error("保存图片时出错：", err);
    return "保存图片时出错";
  }
};

const append_to_json = async (e, data) => {
  let json_path = get_base_path(data.json_path);
  try {
    await fs.writeFile(json_path, data.json_data);
    return true;
  } catch (err) {
    // 文件不存在时返回false,让页面对数据进行缓存
    return false;
  }
};

const open_console = (e,data)=>{
  let win = BrowserWindow.fromWebContents(e.sender);
  win.webContents.openDevTools();
}

const write_text = (e,text)=>{
  return new Promise((res,rej)=>{
    try{
      clipboard.writeText(text);
      res(true);
    }catch(err){
      rej(false);
    }
  })
}

export default {
  get_config,
  open_dialog,
  get_save_path,
  save_file,
  append_to_json,
  open_console,
  write_text
};
